﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SharePointLogBrowser2
{
    public class LogReader
    {
        public LogItemCollection ReadAll(List<FileInfo> list)
        {
            LogItemCollection items = new LogItemCollection();

            list.Reverse();
            foreach (FileInfo fileInfo in list)
            {
                ReadAll(fileInfo.FullName, items);
            }

            return items;
        }
        public LogItemCollection ReadAll(string path)
        {
            LogItemCollection items = new LogItemCollection();

            ReadAll(path, items);

            return items;
        }

        public void ReadAll(string path,  LogItemCollection items)
        {
            
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

                if (!sr.EndOfStream)
                {
                    LogItem previousItem = null;
                    sr.ReadLine();
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        LogItem item = new LogItem(line);
                        if (previousItem != null
                            && previousItem.Message.EndsWith("...")
                            && item.Message.StartsWith("..."))
                        {
                            previousItem.Message += item.Message;
                        }
                        else
                        {
                            items.Add(item);    
                        }
                        previousItem = item;
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
    }
}
